﻿using System;
using System.Collections.Generic;
using System.Linq;
using msilgc.cbuilder.CSyntaxTree;
using msilgc.CSyntaxTree;

namespace msilgc.cbuilder.CBuilder
{
    internal class EvaluationStackHelper {
        private static IEnumerable<ICStatementWithAssignment> StatementsOnStack(CBasicBlock cBasicBlock) {
            return cBasicBlock.Statements
                .Where(stm => stm is ICStatementWithAssignment && ((ICStatementWithAssignment) stm).OnStack)
                .Select(stm => stm as ICStatementWithAssignment);
        }

        public static IVariable PopVariableOffEvaluationStack(CBasicBlock cBasicBlock) {
            if (!StatementsOnStack(cBasicBlock).Any()) {
                throw new Exception("Evalution stack is empty for instruction that wants to pop a value");
            }
            ICStatementWithAssignment statement = StatementsOnStack(cBasicBlock).Reverse().First();
            statement.OnStack = false;
            return statement.Target;
        }

        public static int CurrentEvaluationStackSize(CBasicBlock cBasicBlock) {
            return StatementsOnStack(cBasicBlock).Count();
        }
    }
}